import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Skeleton, Dropdown, Menu } from 'antd';
import { HashRouter, Link, useLocation } from 'react-router-dom';
import { cloneDeep } from 'lodash';
import { routerPrefix } from 'InbizConfig';
import { TextWidget, getMessage } from '@inbiz/react';
import { InbizIcon, isEditorENV, debounce, useApp, getNowPageRoute } from '@inbiz/utils';
// @@后面考虑优化?
import { useNowPageRoute } from '@inbiz/render';
import { getNameData } from '../servies';
import './style.less';

const PageBreadcrumb = (props: { fontSize: number; showIndex: boolean; isJumpUrl?: boolean; emit?: (name: string) => void; }) => {
  const { fontSize, showIndex, isJumpUrl } = props;
  // 数据请求loadding
  // const [loading, $loading] = useState<boolean>(true);
  // 数据
  const [data, $data] = useState<any[]>([]);
  // dom列表数据
  const [domList, $domList] = useState<any[]>([]);
  // 刷新控制
  const [refresh, $refresh] = useState<number>(0);
  // 原始数据
  const rawData = useRef<any[]>([]);
  // 面包屑容器Dom
  const breadcrumbDiv = useRef<any>();
  // hash数据
  const location = useLocation();
  // 站点信息
  const appInfo = useApp();

  const pageRoute = useNowPageRoute();
  const nowPage = getNowPageRoute()

  // 初始化获取数据
  useEffect(() => {
    // 路由数组
    let pathSnippets: any[] = location.pathname.split('/').filter(i => i);
    // 过滤组件内部路由-begin
    const endIdx = pathSnippets.findIndex(i => i == nowPage)
    pathSnippets = pathSnippets.splice(0, endIdx + 1)
    // 过滤组件内部路由-end
    pathSnippets = pathSnippets.map(i => decodeURI(i))
    // 记录是否是页面
    const isPage: boolean = location.pathname.includes('/page/');
    // 是否是处于设计器环境
    const isEditor = isEditorENV();
    /* --------- 去除编辑(editor)和预览(preview)路由 ----------- */
    pathSnippets = pathSnippets.filter((item: string) => !['editor', 'preview'].includes(item));
    /* --------- 去除页面/page前缀 ----------- */
    let findIndex = pathSnippets.indexOf('page');
    if (findIndex > -1) {
      pathSnippets.splice(findIndex, 1);
    }
    /** --------- 查询路由对应名称Name --------- */
    // 根据页面当前路由过滤掉组件无用的自定义路由
    let spliceIndex = 0;
    pathSnippets = pathSnippets.filter((item, i) => {
      if (item == pageRoute) {
        spliceIndex = i;
      }
      if (spliceIndex > 0 && i > spliceIndex) {
        return false;
      }
      return true;
    });

    getNameData({
      siteOutId: appInfo?.SiteInfo?.OutId || '',
      dataVersionId: appInfo?.DataVersionId || '',
      isPage: isPage || isEditor,
      routes: pathSnippets,
    })
      .then((res: any) => {
        makeData(pathSnippets, res);
      })
      .catch(() => {
        makeData(pathSnippets);
      });
  }, [location, showIndex]);

  // 注册页面宽度变化事件执行方法及重算组件显示逻辑
  useEffect(() => {
    const updateSize = debounce({
      fn: () => {
        $refresh(refresh + 1);
      },
      delay: 100,
    });
    window.addEventListener('resize', updateSize);
    if (refresh !== 0) {
      let newDom: any[] = getData(cloneDeep(rawData.current), true);
      $data(newDom);
    }
    return () => window.removeEventListener('resize', updateSize);
  }, [refresh]);

  // 数据变更重组面包屑dom
  useEffect(() => {
    const extraBreadcrumbItems = data.map((_: any, idx: number) => {
      if (!_) {
        return null
      }
      return _?.ellipsis ? (
        <span className="inbiz-page-breadcrumb-list-ellipsis" key={`${_.url}-box-${idx}`}>
          <Dropdown
            overlayClassName={'inbiz-page-breadcrumb-list-ellipsis-dropdown'}
            overlay={() => {
              return (
                <Menu>
                  {_?.children.map((item: any, idx: number) => {
                    return (
                      <Menu.Item key={`${item.url}-${idx}`}>
                        <Link onClick={() => props.emit?.('onClick', item)} key={item.url} to={item.url} style={{ fontSize: fontSize }}>
                          <TextWidget>{item.name}</TextWidget>
                        </Link>
                      </Menu.Item>
                    );
                  })}
                </Menu>
              );
            }}
            placement="bottomLeft"
          >
            <div>
              <InbizIcon type="icon-more1" />
            </div>
          </Dropdown>
          {_.hasMore && <span>/</span>}
        </span>
      ) : (
        <span className="inbiz-page-breadcrumb-list-item" key={`${_.url}-box-${idx}`}>
          {isJumpUrl !== false && (_?.isPage === true || _?.isPage == undefined) ? (
            <>
              <Link onClick={() => {
                props.emit?.('onClick', _)
              }} to={_?.url}>
                <TextWidget>{_?.name}</TextWidget>
              </Link>
            </>
          ) : isJumpUrl ? (
            <span onClick={() => {
              props.emit?.('onClick', _)
            }} style={{ color: '#ddd', cursor: 'not-allowed' }}>
              <TextWidget>{_?.name}</TextWidget>{' '}
            </span>
          ) : (
            <span onClick={() => {
              props.emit?.('onClick', _)
            }} style={{ color: '#333' }}>
              <TextWidget>{_?.name}</TextWidget>{' '}
            </span>
          )}
          <span className="inbiz-page-breadcrumb-xie">/</span>
        </span>
      );
    });
    $domList(extraBreadcrumbItems);
    // $loading(false);
  }, [data]);

  // 组合面包屑路由数据
  const makeData = useCallback(
    (pathSnippets: any[], list = {}) => {
      /* --------- 添加固定预览前缀进面包屑 ----------- */
      let afterList: any[] = showIndex
        ? [
          {
            name: getMessage(appInfo.DefaultPageName),
            url: `${routerPrefix}${appInfo.DefaultPageRoute}`,
          },
        ]
        : [];
      /* --------- 处理全路由及名称 ----------- */
      const listItem = list['Item1'];
      const listItem2 = list['Item2'];
      pathSnippets.forEach((item: any, idx: number) => {
        if (item !== appInfo.DefaultPageRoute && 'page/' + item !== appInfo.DefaultPageRoute) {
          /* --------- 组合路由 ----------- */
          let route: string =
            idx !== 0
              ? afterList[afterList.length - 1].url || ''
              : process.env.NODE_ENV == 'development'
                ? '/preview'
                : '';
          if (location.pathname.includes('/page/')) {
            route += '/page';
          }
          route += `/${item}`;
          /* --------- 配对名称Name后存储 ----------- */
          afterList.push({
            name: listItem[item] || item,
            url: route,
            isPage: listItem2?.[item] || false,
          });
        } else if (!location.pathname.includes('/page/')) {
          // 一级菜单路径是首页时替换首页为对应菜单的数据
          if (showIndex) {
            afterList[0].url = `${routerPrefix}${item}`;
            afterList[0].name = listItem[item] || item;
          } else {
            afterList.push({
              name: listItem[item] || item,
              url: `${routerPrefix}${item}`,
              isPage: listItem2?.[item] || false,
            });
          }
        }
      });
      rawData.current = afterList;

      getData(afterList);
    },
    [location, showIndex],
  );

  //计算数据
  const getData = useCallback((data: any[], update?: boolean): any => {
    // $loading(true);
    let list: any[] = [...data];
    const windowWidth: number = breadcrumbDiv.current?.clientWidth - 44 || 0;
    // 单字符宽度
    const size = fontSize || 14;
    // 省略结束下标
    let endIndex: number = 0;
    // 数据猜想长度
    let wantLength = 0;
    // 计算面包屑首个宽度
    wantLength += (getMessage(data[0]?.name)?.length || 0) * size + 32;
    for (let i = data.length - 1; i > 0; i--) {
      // 单个面包屑字符长度
      let length: number = getMessage(data[i]?.name)?.length || 0;
      // 单个面包屑占用像素
      let oneLength: number = length * size + 32;
      wantLength += oneLength;
      if (wantLength > windowWidth) {
        endIndex = i;
        break;
      }
    }
    if (wantLength < windowWidth) {
      /* --------- 单行显示足够，不特殊处理 ----------- */
      if (update) {
        return cloneDeep(list);
      }
      $data(list);
    } else {
      /* --------- 宽度不足单行显示全，处理省略数据 ----------- */
      let end: any[] = list.slice(endIndex + 1);
      let ellipsis = {
        ellipsis: true,
        hasMore: end.length > 0,
        children: list.slice(1, endIndex + 1),
      };
      let newList: any[] = [list[0]];
      if (ellipsis.children?.length) {
        newList = [...newList, ellipsis]
      }
      if (end?.length) {
        newList = [...newList, ...end]
      }
      if (update) {
        return cloneDeep(newList);
      }
      $data(newList);
    }
  }, []);

  return (
    <div className="inbiz-page-breadcrumb" ref={breadcrumbDiv}>
      {/* <HashRouter> */}
      {/* <Skeleton active loading={loading} title={{ width: '100%' }} paragraph={false}> */}
      <div className="inbiz-page-breadcrumb-list" style={{ fontSize: fontSize }}>
        {domList}
      </div>
      {/* </Skeleton> */}
      {/* </HashRouter> */}
    </div>
  );
};
export default PageBreadcrumb;
